<?php
/**
 * 
 * chat 处理类
 * @author zhouhao
 *
 */
class ChatModel {
	//获得聊天记录
	public function getChat() {
		$url = new Url();
	  	$key = $url->get('key');
	  
	 	$cache = new Cache();
	 	$player_info = $cache->get("ku_".$key);
		$chkRet = Common::checkPlayerInfo($player_info);
		if($chkRet != 0) {
			return array('code'=>$chkRet,'ret'=>'');
		}
		
	   	$GuildId = $player_info["union_id"]; //get guild
		$Nick = $player_info["p_nickname"];
		$UserId = $player_info["u_id"];
		
		//get chat
		$lineid = $url->get('lineid');
		$chatmsgs = array();
		//mute list
		$mutelist = $cache->get("mute_".$UserId);
		//use memcached
		//world channel
		$mkey1 = "0_0";
		$mlines1 = $cache->get($mkey1);
		if($mlines1) {
			$mlines1 = (array)$mlines1;
			while (count($mlines1) > 0) {
				$msg = $mlines1[0];
				if ($msg[0] <= $lineid) {
					array_shift($mlines1);
				} else {
					break;
				}
			}
		}
		if (!$mlines1) {
			$mlines1 = array();
		}
		//guild channel
		$mlines2 = null;
		if ($GuildId > 0) {
			$mkey2 = "1_".$GuildId;
			$mlines2 = $cache->get($mkey2);
			if($mlines2) {
				$mlines2 = (array)$mlines2;
				while(count($mlines2) > 0) {
					$msg = $mlines2[0];
					if($msg[0] <= $lineid) {
						array_shift($mlines2);
					}
					else {
						break;
					}
				}
			}
		}
		if (!$mlines2) {
			$mlines2 = array();
		}
		//personanl
		$mkey3 = "2_".$UserId;
		$mlines3 = $cache->get($mkey3);
		if ($mlines3) {
			$mlines3 = (array)$mlines3;
			while (count($mlines3) > 0) {
				$msg = $mlines3[0];
				if ($msg[0] <= $lineid) {
					array_shift($mlines3);
				} else {
					break;
				}
			}
		}
		if (!$mlines3) {
			$mlines3 = array();
		}
		//sys world
		$mkey4 = "sys0_0";
		$mlines4 = $cache->get($mkey4);
		if($mlines4) {
			$mlines4 = (array)$mlines4;
			while(count($mlines4) > 0) {
				$msg = $mlines4[0];
				if ($msg[0] <= $lineid) {
					array_shift($mlines4);
				} else {
					break;
				}
			}
		}
		if (!$mlines4) {
			$mlines4 = array();
		}
		//sys guild channel
		$mlines5 = null;
		if ($GuildId > 0) {
			$mkey5 = "sys1_".$GuildId;
			$mlines5 = $cache->get($mkey5);
			if($mlines5) {
				$mlines5 = (array)$mlines5;
				while (count($mlines5) > 0) {
					$msg = $mlines5[0];
					if ($msg[0] <= $lineid) {
						array_shift($mlines5);
					} else {
						break;
					}
				}
			}
		}
		if (!$mlines5) {
			$mlines5 = array();
		}
		//sys personanl
		$mkey6 = "sys2_".$UserId;
		$mlines6 = $cache->get($mkey6);
		if ($mlines6) {
			$mlines6 = (array)$mlines6;
			while(count($mlines6) > 0) {
				$msg = $mlines6[0];
				if($msg[0] <= $lineid) {
					array_shift($mlines6);
				} else {
					break;
				}
			}
		}
		if (!$mlines6) {
			$mlines6 = array();
		}
		if ($mutelist) {
			for ($i=0; $i<count($mlines1); $i++) {
				$msg = &$mlines1[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;//第7位
				}
			}
			for ($i=0;$i<count($mlines2);$i++) {
				$msg = &$mlines2[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;
				}
			}
			for ($i=0;$i<count($mlines3);$i++) {
				$msg = &$mlines3[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;
				}
			}
			for ($i=0;$i<count($mlines4);$i++) {
				$msg = &$mlines4[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;
				}
			}
			for ($i=0; $i<count($mlines5); $i++) {
				$msg = &$mlines5[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;
				}
			}
			for ($i=0;$i<count($mlines6);$i++) {
				$msg = &$mlines6[$i];
				if (array_key_exists(intval($msg[1]), $mutelist)) {
					$msg[5] = '***';
					$msg[7] = 1;
				}
			}
		}
		$chatmsgs['p'] = array(0=>$mlines1,1=>$mlines2,2=>$mlines3);
		$chatmsgs['s'] = array(0=>$mlines4,1=>$mlines5,2=>$mlines6);
		
		//events
		//typeid=1，表示有新城堡建立
		//typeid=2，表示有新邮件
		//typeid=3，表示需要刷新cityinfo
		//typeid=4，表示需要刷新userinfo(full sync)
		//typeid=5，显示信息
		//typeid=6，已获得礼包
		//typeid=7，表示需要刷新cd
		//typeid=8，检查版本更新
		//typeid=9，获取userinfo
		//typeid=10，获取giftinfo
		//typeid=11，获取events
		//typeid=12，获取status
		//typeid=13，新pvp战报
		//typeid=14，有待领奖励的任务
		$events = $cache->get("e_".$UserId);
	    if (!$events) {
	    	$events = array();
	    } else {
	    	//clear events
	    	$cache->delete("e_".$UserId);
	    }
		
		/*todo:通知是否有已完成的任务
		$cities=$cache->get("kc_".$key);
		if(hasFinishedQuest($memcache, $db, $player_info, $cities, 0))
		{
			$eventmsg = array("typeid"=>14);
			array_push($events,$eventmsg);
		}
		*/
		
		return array('code'=>0,'ret'=>array('msg'=>$chatmsgs, 'evt'=>$events));
	
	}
	
	//发送聊天操作
	public function sendChat() {
		$maxlines = 30;
		
		$url = new Url();
	  	$key = $url->get('key');
	  
	 	$cache = new Cache();
	 	 $player_info = $cache->get("ku_".$key);
		$chkRet = Common::checkPlayerInfo($player_info);
		if ($chkRet != 0) {
			return array('code'=>$chkRet,'ret'=>'');
		}
		
	 	$GuildId = $player_info["union_id"]; //get guild
		$Nick = $player_info["p_nickname"];
		$UserId = $player_info["u_id"];
		
		$timestamp = time();//send chat
		$banchat = $cache->get("banchat_".$UserId);//check ban chat
		if ($banchat) {
			if ($banchat <= $timestamp) {
				$cache->delete("banchat_".$UserId);//time out
			} else {
				$bantext = $lng_data['chat_banned']." ";
				$secsleft = $banchat - $timestamp;
				$days = floor($secsleft/86400);
				$bantext = $bantext.$days." ".$lng_data['days']." ";
				if ($days == 0) {
					$hours = floor($secsleft/3600);
					$bantext = $bantext.$hours." ".$lng_data['hours']." ";
					if ($hours == 0) {
						$mins = floor($secsleft/60);
						$bantext = $bantext.$mins." ".$lng_data['mins']." ";
						if ($mins == 0) {
							$bantext = $bantext.$secsleft." ".$lng_data['secs'];
						}
					}
				}
				$eventmsg = array("typeid"=>5,"txt"=>$bantext);
				$cache->setEvent($UserId, $eventmsg);
		   		return array('code'=>501,'ret'=>'');
			}
		}
		
		$txt = trim(urldecode($url->get('txt')));
		if (strlen($txt) == 0) {
		  	return array('code'=>0,'ret'=>'');
		}
		$db = new Data();
		$pos = strpos($txt, ':mute');//mute
		if ($pos !== false && $pos == 0) {
			$nickname = substr($txt,6);
			$query=$db->query("select u_id from player_info where p_nickname = '".$nickname."'");
			$m=$db->fetch_array($query);
			if(!$m) {
				return array('code'=>504,'ret'=>'');
			}
			$muteid=intval($m['u_id']);
			$mutelist = $cache->get("mute_".$UserId);
			if (!$mutelist) {
				$mutelist = array($muteid=>1);
			} else {
				$mutelist[$muteid] = 1;
			}
			$cache->set("mute_".$UserId,$mutelist);
			return array('code'=>0,'ret'=>'');
		}
		//unmute
		$pos = strpos($txt, ':unmute');
		if($pos !== false && $pos == 0) { //unmute
			$nickname = substr($txt,8);
			$query=$db->query("select u_id from player_info where p_nickname = '".$nickname."'");
			$m=$db->fetch_array($query);
			if (!$m) {
				return array('code'=>5001,'ret'=>'');
			}
			$muteid=intval($m['u_id']);
			$mutelist = $cache->get("mute_".$UserId);
			if ($mutelist && array_key_exists($muteid, $mutelist)) {
				unset($mutelist[$muteid]);
			}
			$cache->set("mute_".$UserId,$mutelist);
			return array('code'=>0,'ret'=>'');
		}
		//ban chat
		$pos = strpos($txt, ':ban');
		if ($pos !== false && $pos == 0) {
			if (($player_info["role"] & 1) == 0) { //ban
				return array('code'=>4,'ret'=>''); //not authenticated
			}
			
			$nickname = substr($txt,5);//:ban lordname
			$query=$db->query("select u_id from player_info where p_nickname = '".$nickname."'");
			$m=$db->fetch_array($query);
			if (!$m) {
				return array('code'=>5001,'ret'=>'');
			}
			$muteid=intval($m['u_id']);
			$cache->set("banchat_".$muteid, $timestamp+3600);
			//save log
			$extinfo = '';
			$mkey1 = "0_0";
			$mlines1 = $cache->get($mkey1);
			if ($mlines1 != false) {
				$mlines1 = (array)$mlines1;
				$lastmsg1 = array_pop($mlines1);
				$i=0;
				while ($i<10 && $lastmsg1 != NULL) { //最近10条聊天信息作为log
					if($lastmsg1["from_id"] == $muteid) {
						$extinfo = $extinfo.$lastmsg1['line_txt'].'\r\n';
						$i++;
					}
					$lastmsg1 = array_pop($mlines1);
				}
			}
			$db->query("insert into banchat_log (u_id, to_u_id, time_start, time_length, optype, info) values (".$UserId.",".$muteid.",".$timestamp.",3600,1,'".$extinfo."')");
			
			return array('code'=>0,'ret'=>'');
		}
		
		$pos = strpos($txt, ':unban'); //unban chat
		if ($pos !== false && $pos == 0) {
			if (($player_info["role"] & 1) == 0) { //unban
				return array('code'=>4,'ret'=>''); //not authenticated
			}
			$nickname = substr($txt,7); //:unban lordname
			$query=$db->query("select u_id from player_info where p_nickname = '".$nickname."'");
			$m=$db->fetch_array($query);
			if (!$m) {
				return array('code'=>5001,'ret'=>'');
			}
			$muteid=intval($m['u_id']);
			$cache->delete("banchat_".$muteid);
			//save log
			$db->query("insert into banchat_log (u_id, to_u_id, time_start, time_length, optype, info) values (".$UserId.",".$muteid.",".$timestamp.",0,2,'')");
			return array('code'=>0,'ret'=>'');
		}
		
		$notice=false; //notification
		$pos = strpos($txt, ':notice');
		if($pos !== false && $pos == 0) {
			if(($player_info["role"] & 1) == 0) { //notice
				return array('code'=>4,'ret'=>'');//not authenticated
			}
			$notice=true;//:notice msg
			$txt = substr($txt,8);
		}
		
		$battlereport = 0;//share battle report
		$battleview = 0;
		$pos = strpos($txt, ':report');
		if ($pos !== false && $pos == 0) {
			$txt = substr($txt,9);//reportid,msg
			$params = explode(" ",$txt);
			$battlereport=intval($params[0]);
			$txt = substr($txt,strlen($params[0])+1);
			$query=$db->query("select w_id,u_id,to_u_id from war_result where w_id = '".$battlereport."' and (u_id = ".$UserId." or to_u_id = ".$UserId.")");
			$m=$db->fetch_array($query);
			if (!$m) {
				$battlereport = 0;//invalid battlereport
			} else {
				if($m['u_id'] == $UserId) {
					$battleview = 1;
				}
			}
		}
		
		$targetid = $url->get('targetid');//get more parameters
		$targettype = $url->get('targettype');
		if ($targettype == 1 && $targetid != $GuildId) {
			return array('code'=>503,'ret'=>'');//send to wrong guild
		} else if($targettype == 2) {
			$mutelist = $cache->get("mute_".$targetid);//private chat
			if ($mutelist && array_key_exists($UserId, $mutelist)) {
				return array('code'=>0,'ret'=>'');//in ban list: done send
			}
		}
		$txt = strip_tags($txt);
		/*
		$chat_char_limit=array("'","\"");
	    foreach ($chat_char_limit as $m){
	       //replace
	       $txt = str_replace($m, '', $txt);
	    }
	    */
	    $txtlow = mb_strtolower($txt,'utf-8');
	    $chat_limit=array("fuck","cock","dick","pussy","cunt","asshole","bitch","whore","bastard","hooker","nigger","blow","penus","sex","slut");
	    if(string_has_any($txtlow, $chat_limit)) {
	  		return array('code'=>505,'ret'=>'');
	  	}
	  
	  	if(strlen($txt) > 128) {
	  		$txt = substr($txt, 0, 128);
	  	}
	  	if($notice) {
	  		$txt = "<b>".$txt."</b>";
	  	}
	  	$ico='';
	  	if (($player_info["role"] & 1) != 0) {
	  		$ico='misc/star1.png';
	  	}
		$a=$timestamp;$b=microtime();$b=substr($b,2,2);$c=$a.$b;
		$query="INSERT INTO blte_lines () VALUES(".$c.",".$UserId.",'".$Nick."',".$timestamp.",'".$txt."',".$targettype.",".$targetid.")";
		$db->query($query);
		//use memcached
		$mkey = (string)$targettype."_".$targetid;
		$mmsg = array($c,(int)$UserId,$Nick,$targettype,$targetid,stripslashes($txt),$ico,0,intval($player_info["p_country"]),$battlereport,$battleview);//第7位标志是否mute，默认为否
		$mlines = $cache->get($mkey);
		if (!$mlines) {
			//the first chat msg
			$mlines = array($mmsg);
			$cache->set($mkey, $mlines);
		} else {
			$mlines = (array)$mlines;
			array_push($mlines, $mmsg);//顺序：从新到旧
			while (count($mlines) > $maxlines) {
				array_shift($mlines);
			}
			$cache->set($mkey, $mlines);
		}
		if ($targettype == 2) {//private chat: also insert the chat text into my queue
			$mkey = (string)$targettype."_".$UserId;
			$mlines = $cache->get($mkey);
			if (!$mlines) {//the first chat msg
				$mlines = array($mmsg);
				$cache->set($mkey, $mlines);
			} else {
				$mlines = (array)$mlines;
				array_push($mlines, $mmsg);//顺序：从新到旧
				while (count($mlines) > $maxlines) {
					array_shift($mlines);
				}
				$cache->set($mkey, $mlines);
			}
		}
		return array('code'=>0,'ret'=>'');
	}
}
?>